
$(function() {
  $.pageRuler()


  var link = 'http://120.78.130.251:9527';
  var len, wid //容器长宽(m)
  var h , w //容器高宽（px）
  var lines, columns //网格行数、列数
  var window_height = window.innerHeight;
  //var date = new Date()
  //var current_year = date.getFullYear()
  //var year = 2018
  var line_spacing = 0.65 // 行距
  var row_spacing = 0.3 // 株距
  var string = window.location.search
  var str = string.split('=')[1]
  console.log(str);
  $.ajax({
    type: 'POST',
    url: link+'/farm/getFarmList',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ 'farmlandId': str }),
    dataType: 'json',
    async:false,
    success: function(data) {
      console.log(data);
      len=data.rows[0].length;
      wid=data.rows[0].width;
      console.log(wid) //宽度 50
      console.log(len) //高度40
      w=parseInt(wid/row_spacing/5*50)
      h=parseInt(len/line_spacing*20)
      lines = Math.ceil(len / line_spacing) // 容器行数
      temp2 = Math.ceil(wid / row_spacing)
      columns = Math.ceil(temp2 / 5) // 容器列数

      var parent = document.getElementById('parent')
      parent.style.height = 0.8 * window_height +'px'


      parent.setAttribute('style', 'grid-template-columns:repeat(' + columns + ',50px)')
      for (var i = 0; i < lines; i++) {
        for (var j = 0; j < columns; j++) {
          var x = document.createElement('div')
          x.classList.add('column')
          x.setAttribute('flag', i + ' ' + j)
          parent.appendChild(x)
        }
      }
      var son = document.getElementById('containment-wrapper')

      son.style.width = w + 'px' // 框架宽高
      son.style.height = h + 'px'
    },
    error: function(message) {
      console.log("error")
    }
  })
  // len = 50 // prompt("请输入试验田长度");
  // wid = 40 // prompt("请输入试验田宽度");
  // len = 150;
  // wid = 150;
  var myGrids = new Array()
  var myExps = new Array()
  var json1 = []
  var species = []
  var tempId = ''

  // $.ajax({
  //   type: 'POST',
  //   url: 'http://120.78.130.251:9527/localspecies/getLocalSpecies',
  //   contentType: 'application/json; charset=utf-8',
  //   data: JSON.stringify({}),
  //   dataType: 'json',
  //   success: function(data) {
  //     for (i = 0; i < data.total; i++) {
  //       species.push(data.rows[i].speciesId)
  //     }
  //     console.log('品种数:' + species.length + ',,,' + species[2])
  //   },
  //   error: function(message) {
  //   }
  // })
  var type = getExpType()
  var sel = document.getElementById('sel')
  for (var typeNo = 0; typeNo < type.length; typeNo++) {
    var expName = type[typeNo]['exType']
    sel.options.add(new Option(expName, expName))
  }

  var width1 = document.getElementsByClassName('column')[0].clientWidth;
  var height1 = document.getElementsByClassName('column')[0].clientHeight;

  console.log(type);
  reading(w,width1,height1);

  $('.confirm1').click(function() {
    var plotId = $('#pId').val()
    if (plotId === '') {
      alert('请填写试验田ID' +  this.GLOBAL.testLink)
    } else {
      var species_num = $('#species_num').val()
      if (species_num === '') {
        alert('请填写品种数量')
      } else {
        if (species_num > 10000) {
          alert('品种数量过多')
        } else {
          for (var i = 0; i < species_num; i++) {
            var a = i + 1
            var sId = plotId + '(' + a + ')'
            console.log(sId)
            //var text = document.createElement('input')
            //text.setAttribute('type', 'text')
            //text.setAttribute('placeholder', 'id:' + plotId + '品种:' + a)
            //text.setAttribute('id', sId)
            //document.getElementById('drag').appendChild(text)
          }
          var regular = $('#sel').val()
          var p = 0
          for (var q = 0; q < type.length; q++) {
            if (regular === type[q]['exType']) {
              p = q
            } else {
            }
          }
          // regular = regular.slice(1, regular.length - 1).split(',')
          // var in_row=$("#in_row").val();
          // var in_col=$("#in_col").val();
          var in_row = parseFloat(type[p]['row']) // 行 占几行
          var in_col = parseInt(type[p]['repeat']) // 重复
          var zhu = parseFloat(type[p]['zhu']) / 5 // 株/5 占几格
          var expType = regular;
          var color = type[p]['color']
          console.log(expType)
          var width = document.getElementsByClassName('column')[0].clientWidth
          var height = document.getElementsByClassName('column')[0].clientHeight
          // console.log(in_row,in_col,zhu);
          //width = (width + 1) * zhu * species_num
          //height = (height + 0.8) * in_row

          width = (width + 1) * zhu;
          height = (height + 0.8) * species_num * in_row;
          var area = document.createElement('ul')

          area.setAttribute('id', plotId);
          area.setAttribute('name', expType);
          area.setAttribute('color', color);
          area.setAttribute('sNum', species_num);
          area.classList.add('in_p', 'in', 'draggable', 'ui-widget-content')
          area.style.height = height + 'px'
          document.getElementById('containment-wrapper').appendChild(area)
          for (var i = 0; i < in_col; i++) {
            var t = document.createElement('li')
            //t.style.cssFloat="left";
            //var text = document.createTextNode(regular + ' ' + type[p]['row'] + '行' + type[p]['zhu'] * species_num + '株' + ' ' + species_num + '品种')
            var text1 = document.createTextNode(regular + "\n" + species_num + "品种");
            //var text2 = document.createTextNode(species_num + "品种");
            t.appendChild(text1);
            //t.appendChild(text2);
            t.style.width = width + 'px'
            t.style.height = height + 'px'
            t.style.backgroundColor = color

            if (i === 0) {
              t.style.marginRight = 0 + 'px';
            }
            //console.log(area.style.height + "+" + h)
            if(parseInt(area.style.height) < h){
              area.appendChild(t)
            }
            else {
              alert("品种数量过多")
              return
            }
            //area.appendChild(t)
          }
          area.ondblclick = function() {
            var res = confirm('是否确认删除？')
            if (res == true) {
              document.getElementById('containment-wrapper').removeChild(this)
              var index = myGrids.indexOf(this)
              if (index > -1) {
                myGrids.splice(index, 1)
              }
              console.log(this)
              console.log(myGrids)
            }
            else {
            }
          }
          //getExps(plotId)
          myGrids.push(plotId)
          //var button = document.getElementById('generate')
          //button.style.display = 'none'
          $('#drag').html('')
          $('.draggable').draggable({ scroll: true, containment: '#containment-wrapper' })

          return false

          // text.onchange = function() {
          //   if (species.indexOf(this.value) < 0) {
          //     console.log(this.value)
          //     alert('请输入准确品种ID')
          //     this.value = ''
          //   } else {
          //     console.log(species.indexOf(this.value))
          //   }
          // }
        }
    }
  }
  })
      //var button = document.getElementById('generate')
      //button.style.display = 'block'

    //  var button = document.createElement("button");
    //  button.setAttribute("class","confirm");
    //  button.innerHTML = "确认生成";
    //  document.getElementById('drag').appendChild(button);
  // $('.confirm').click(function() {
  //   var plotId = $('#pId').val()
  //   var species_num = $('#species_num').val()
  //   var regular = $('#sel').val()
  //   var p = 0
  //   for (var q = 0; q < type.length; q++) {
  //     if (regular === type[q]['exType']) {
  //       p = q
  //     } else {}
  //     console.log(p)
  //   }
  //   // regular = regular.slice(1, regular.length - 1).split(',')
  //   // var in_row=$("#in_row").val();
  //   // var in_col=$("#in_col").val();
  //
  //   var in_row = parseFloat(type[p]['row']) // 行 占几行
  //   var in_col = parseInt(type[p]['repeat']) // 重复
  //   var zhu = parseInt(type[p]['zhu']) / 5 // 株/5 占几格
  //   var expType = regular
  //   var color = type[p]['color']
  //   console.log(expType)
  //   var width = document.getElementsByClassName('column')[0].clientWidth
  //   var height = document.getElementsByClassName('column')[0].clientHeight
  //   // console.log(in_row,in_col,zhu);
  //   width = (width + 1) * zhu * species_num
  //   height = (height + 0.8) * in_row
  //
  //   var area = document.createElement('ul')
  //
  //   area.setAttribute('id', plotId)
  //   area.setAttribute('name', expType)
  //   area.setAttribute('color', color)
  //   area.setAttribute('sNum', species_num)
  //   area.classList.add('in_p', 'in', 'draggable', 'ui-widget-content')
  //   area.style.height = height + 'px'
  //   document.getElementById('containment-wrapper').appendChild(area)
  //   for (var i = 0; i < in_col; i++) {
  //     var t = document.createElement('li')
  //     var text = document.createTextNode(regular + ' ' + type[p]['row'] + '行' + type[p]['zhu'] * species_num + '株' + ' ' + species_num + '品种')
  //     t.appendChild(text)
  //     t.style.width = width + 'px'
  //     t.style.height = height + 'px'
  //     t.style.backgroundColor = color
  //
  //     if (i === 0) {
  //       t.style.marginRight = 0
  //     }
  //
  //     area.appendChild(t)
  //   }
  //   area.ondblclick = function() {
  //     var res = confirm('是否确认删除？')
  //     if (res == true) {
  //       document.getElementById('containment-wrapper').removeChild(this)
  //       var index = myGrids.indexOf(this)
  //       if (index > -1) {
  //         myGrids.splice(index, 1)
  //       }
  //       console.log(this)
  //       console.log(myGrids)
  //     } else {}
  //   }
  //   getExps(plotId)
  //   myGrids.push(plotId)
  //   //var button = document.getElementById('generate')
  //   button.style.display = 'none'
  //   $('#drag').html('')
  //   $('.draggable').draggable({ scroll: true, containment: '#containment-wrapper' })
  //
  //   return false
  // })

  // $('.finish').click(function() {
  //   var tb0 = '<tr>\n' +
  //           '                <th>ID</th>\n' +
  //           '                <th>实验类型</th>\n' +
  //           '                <th>品种数</th>\n' +
  //           '                <th>坐标</th>\n' +
  //           '                <th>操作</th>\n' +
  //           '            </tr>'
  //   // $("#drag").html('');
  //   $('#tb').html(tb0)
  //   for (var i = 0; i < myGrids.length; i++) {
  //     var move_X = document.getElementById(myGrids[i]).offsetLeft
  //     var move_Y = document.getElementById(myGrids[i]).offsetTop
  //     var expType = document.getElementById(myGrids[i]).getAttribute('name')
  //     var species_num = document.getElementById(myGrids[i]).getAttribute('sNum')
  //     // console.log( move_X);
  //     // console.log( move_Y);
  //     // var html1 = document.getElementById("drag").innerHTML;
  //     // $("#drag").html(html1+"\<br\>"+"id: "+ myGrids[i]+" 横坐标: "+ move_X+"px 纵坐标: "+move_Y+"px");
  //
  //     var tab = '<tr><td>' + myGrids[i] + '</td><td>' + expType + '</td><td>' + species_num + '</td><td>' + ' 横坐标: ' + move_X + 'px 纵坐标: ' + move_Y + 'px' + '</td><td><button>进入</button><button>编辑</button><button>删除</button></td></tr>'
  //     var html2 = document.getElementById('tb').innerHTML
  //     $('#tb').html(html2 + tab)
  //   }
  //
  //   return false
  // })
  $('.cancel').click(function() {
    var res = confirm('是否确认删除？')
    if (res === true) {
      var oDiv = $('.in_p')
      document.getElementById('containment-wrapper').removeChild(oDiv[oDiv.length - 1])
      myGrids.length--
    } else {

    }
    return false
  })

  $('.save').click(function(e) {
    var res = confirm('是否确认保存？')
    if (res === true) {
      e.preventDefault();
      var json = []
      // var json1 = []
      var string = window.location.search
      var farmlandId = string.split('=')[1]
      for (var i = 0; i < myGrids.length; i++) {
        var move_X = document.getElementById(myGrids[i]).offsetLeft
        var move_Y = document.getElementById(myGrids[i]).offsetTop
        var movex = move_X + document.getElementById(myGrids[i]).offsetWidth
        var movey = move_Y + document.getElementById(myGrids[i]).offsetHeight
        var expType = document.getElementById(myGrids[i]).getAttribute('name')
        var species_num = document.getElementById(myGrids[i]).getAttribute('sNum')
        var color = document.getElementById(myGrids[i]).getAttribute('color')
        var row = {
          'name': myGrids[i],
          'expType': expType,
          'moveX': move_X,
          'moveY': move_Y,
          'moveX1': movex,
          'moveY1': movey,
          'num': species_num,
          'color': color,
          'farmlandId': farmlandId,
          //'year': year
          'rows' : 1
        }
        json.push(row)
        // console.log(json);
      }

      $('#request-process-patent').html('正在提交数据，请勿关闭当前窗口...')
      $.ajax({
        type: 'POST',
        url: link+'/farm/addFieldPlan',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(json),
        dataType: 'json',
        success: function(message) {
          if (message > 0) {
            alert('请求已提交！')
          }
        },
        error: function(message) {
          alert('提交数据失败！' + i)
        }
      })
      alert('保存成功')
    } else {
    }
    // 生成文件
    //var filename = farmlandId + '_' + year
    var str_json = JSON.stringify(json)
    export_raw(filename, str_json)
    e.preventDefault();
    // var str_json1=JSON.stringify(json1);
    // export_raw('myExps.json', str_json1);
  })
  $('.read').click(function() {
    // year = prompt('请输入试验田年份', current_year - 1)
    // while (year == null) {
    //   alert('年份不能为空')
    //   year = prompt('请输入试验田年份', current_year - 1)
    // }
    reading()
  })

  $('.browse').click(function() {

    window.open('browse.html?farmlandId=' + str)
  })

  function reading(w,width1,height1) {
    var string = window.location.search
    var str = string.split('=')[1]
    console.log(str)
    // $.getJSON("http://120.78.130.251:9527/experimentfield/getExperimentFieldList", {"farmlandId":"011"}, function (data){
    $.ajax({
      url: link+'/farm/getExperimentFields',
      type: 'GET',
      contentType: 'application/json; charset=UTF-8',
      async: false,
      dataType: 'json',
      data: { 'farmId': str },
      success: function(data) {
        console.log(data)
        var $jsontip = $('#jsonTip')
        // var strHtml = ''
        // 存储数据的变量
        $jsontip.empty()
        // 清空内容
        number = data.total
        var json = data.rows
        var p = 0
        for (var i = 0; i < number; i++) {
          var plotId = json[i].id
          var species_num = json[i].num
          var regular = json[i].expType
          for (var q = 0; q < type.length; q++) {
            if (regular == type[q]['exType']) {
              p = q
            } else {
            }
          }
          // regular = regular.slice(1, regular.length - 1).split(',')
          // var in_row=$("#in_row").val();
          // var in_col=$("#in_col").val();

          var in_row = parseFloat(type[p]['row']) // 行 占几行
          var in_col = parseInt(type[p]['repeat']) // 重复
          var zhu = parseInt(type[p]['zhu']) / 5 // 株/5 占几格
          var expType = regular
          var color = type[p]['color']
          console.log(expType)

          //var width = document.getElementsByClassName('column')[0].clientWidth
          //var height = document.getElementsByClassName('column')[0].clientHeight
          // console.log(in_row,in_col,zhu);
          // var width = 50;
          // var height = 20;
          width = (width1 + 1) * zhu
          height = (height1 + 0.8) * species_num * in_row
          //console.log("0=====>"+width+height);
          // 创建土地区域
          var area = document.createElement('ul')

          area.setAttribute('id', plotId)
          area.setAttribute('name', expType)
          area.setAttribute('color', color)
          area.setAttribute('sNum', species_num)
          area.classList.add('in_p', 'in', 'draggable', 'ui-widget-content')
          area.style.color = color
          area.style.height = height + 'px'
          document.getElementById('containment-wrapper').appendChild(area)

          area.style.marginTop = parseInt(json[i].moveY) + 'px'
          // area.style.marginBottom =(parseInt(json["move_y1"])+2)+'px';
          // area.style.marginLeft = parseInt(json["moveX"])+'px';
          area.style.marginRight = (w - parseInt(json[i].moveX1)) + 'px';
          // var color=getRandomColor();
          for (var j = 0; j < in_col; j++) {
            var t = document.createElement('li');
            var text = document.createTextNode(regular + ' ' + species_num + '品种');
            var span = document.createElement('span');
            span.style.color = '#000000';
            span.appendChild(text);
            t.appendChild(span);

            t.style.width = width + 'px';
            t.style.height = height + 'px';
            t.style.backgroundColor = color;
            if (j === 0) {
              t.style.marginRight = 0 +'px';
            }
            area.appendChild(t);
          }

          area.onclick = function() {
            // deleteElement(plotId);
            this.style.marginTop = 0 + 'px';
            this.style.marginRight = 0 + 'px';
            $('.draggable').draggable({ scroll: true, containment: '#containment-wrapper' })
          }
          area.ondblclick = function() {
            var res = confirm('是否确认删除？')
            if (res == true) {
              document.getElementById('containment-wrapper').removeChild(this)
              var index = myGrids.indexOf(this)
              if (index > -1) {
                myGrids.splice(index, 1)
              }
              console.log(this)
              console.log(myGrids)
            } else {}
          }
          myGrids.push(plotId)
        }
      }
    })
  }

  function export_raw(filename, content) {
    var eleLink = document.createElement('a')
    eleLink.download = filename
    eleLink.style.display = 'none' // 字符内容转变成blob地址
    var blob = new Blob([content])
    eleLink.href = URL.createObjectURL(blob) // 触发点击
    document.body.appendChild(eleLink)
    eleLink.click() // 然后移除
    document.body.removeChild(eleLink)
  }
  // function getExps(id) {
  //   var commontest = []
  //   var species = new Array()
  //   var species_num = document.getElementById(id).getAttribute('sNum')
  //   var exp = document.getElementById(id).getAttribute('name')
  //   for (var num = 1; num <= species_num; num++) {
  //     var speciesId = document.getElementById(id + '(' + num + ')').value
  //     var row2 = { 'speciesId': speciesId, 'experimentType': exp }
  //
  //     $.ajax({
  //       type: 'POST',
  //       url: 'http://120.78.130.251:9527/SpeciesCommontest/addCommontest',
  //       contentType: 'application/json; charset=utf-8',
  //       data: JSON.stringify(row2),
  //       dataType: 'json',
  //       success: function(message) {
  //         console.log(row2)
  //       },
  //       error: function(message) {
  //       }
  //     })
  //
  //     species.push(speciesId)
  //     commontest.push(row2)
  //   }
  //   var row1 = { 'id': id, 'num': species_num, 'speciesId': species }
  //
  //   json1.push(row1)
  //
  //   $('#request-process-patent').html('正在提交数据，请勿关闭当前窗口...')
  //   $.ajax({
  //     type: 'POST',
  //     url: 'http://120.78.130.251:9527/Block/putInnerSpeciesWithExpList',
  //     contentType: 'application/json; charset=utf-8',
  //     data: JSON.stringify(json1),
  //     dataType: 'json',
  //     success: function(message) {
  //       if (message > 0) {
  //       }
  //     },
  //     error: function(message) {
  //
  //     }
  //   })
  // }
  function getExpType() {
    var expType = new Array()
    $.ajax({
      type: 'GET',
      url: 'myExps.json',
      dataType: 'json',
      // data: null,
      async: false,
      success: function(data) {
        expType = data
      }
    })
    console.log(expType)
    return expType
  }
  $('.container').resizable({
    aspectRatio: 16 / 9
  })

  $('.smaller').click(function() {
    $('.column').css({ 'width': '10px', 'height': '10px' })
  })
})
